<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Promotion\Ctl;

use Srv\Apps\Proto\DTO\Promotion\AdRewardConfAddDTO;
use Srv\Apps\Proto\DTO\Promotion\AdRewardConfEditDTO;
use Srv\Apps\Proto\DTO\Promotion\AdRewardConfListDTO;
use Srv\Apps\Proto\Enum\AdRewardTypeEnum;
use Srv\Apps\Proto\Enum\YesOrNoEnum;
use Srv\Apps\Proto\VO\Promotion\AdRewardConfListVO;
use Srv\Apps\Proto\VO\Promotion\AdRewardConfVO;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Common\CommTime;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Frame\Page;
use Srv\Libs\Storage\DataMysql;

final class AdRewardConfCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;     // DB-Write
    private array $backUrlList              = [
        AdRewardTypeEnum::AD_REWARD_TYPE_GROMORE    => 'https://apidevxc.nilela.com/api/ad/back/gromore/{ADID}',   // 穿山甲聚合
        AdRewardTypeEnum::AD_REWARD_TYPE_CSJ        => 'https://apidevxc.nilela.com/api/ad/back/csj/{ADID}',       // 穿山甲-单个
        AdRewardTypeEnum::AD_REWARD_TYPE_YLH        => 'https://apidevxc.nilela.com/api/ad/back/ylh/{ADID}',       // 优量汇
    ];

    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
        }
        if($thisObject->isRelease()){
            $thisObject->backUrlList        = [
                AdRewardTypeEnum::AD_REWARD_TYPE_GROMORE    => 'https://xctv-api.xc.com/api/ad/back/gromore/{ADID}',   // 穿山甲聚合
                AdRewardTypeEnum::AD_REWARD_TYPE_CSJ        => 'https://xctv-api.xc.com/api/ad/back/csj/{ADID}',       // 穿山甲-单个
                AdRewardTypeEnum::AD_REWARD_TYPE_YLH        => 'https://xctv-api.xc.com/api/ad/back/ylh/{ADID}',       // 优量汇
            ];
        }
        return $thisObject;
    }

    /**
     * @param int $adrcId
     * @return array
     * getAdRewardConfSrc
     */
    public function getAdRewardConfSrc(int $adrcId):array
    {
        if($adrcId < 1) return [];
        $isFail     = false;
        $info       = $this->DbAuto->getDataOne('SELECT adrc_id, adrc_type, adrc_adid, adrc_key, adrc_remark, adrc_status, adrc_create_time, adrc_update_time FROM '.$this->DbAuto->getTableNameAll('ad_reward_config').' WHERE adrc_id='.$adrcId.' AND adrc_delete=0', $isFail);
        if($isFail || !isset($info['adrc_id'])) return [];
        return $info;
    }

    /**
     * @param array $adrcIdList
     * @return array
     * getAdRewardConfSrcBatch
     */
    public function getAdRewardConfSrcBatch(array $adrcIdList):array
    {
        if(count($adrcIdList) < 1) return [];
        $isFail     = false;
        $list       = $this->DbAuto->getData('SELECT adrc_id, adrc_type, adrc_adid, adrc_key, adrc_remark, adrc_status, adrc_create_time, adrc_update_time FROM '.$this->DbAuto->getTableNameAll('ad_reward_config').' WHERE adrc_id IN('.implode(',', $adrcIdList).') AND adrc_delete=0', $isFail);
        if($isFail || count($list) < 1) return [];
        $listData   = [];
        foreach ($list as $item){
            $adrcIdItem             = intval($item['adrc_id']??0);
            if($adrcIdItem < 1) continue;
            $listData[$adrcIdItem]  = $item;
        }
        return $listData;
    }

    /**
     * @param Page $Page
     * @param $whereData
     * @return AdRewardConfListVO|null
     * getAdRewardConfList
     */
    public function getAdRewardConfList(Page $Page, $whereData):?AdRewardConfListVO
    {
        $limitString        = $Page->getLimitString();
        $whereString        = ' WHERE adrc_delete=0';
        // 检索条件
        if(count($whereData) > 0)foreach ($whereData as $key => $val){
            switch ($key){
                case AdRewardConfListDTO::_adrcId:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'adrc_id='. intval($val);
                    break;
                case AdRewardConfListDTO::_type:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'adrc_type='. intval($val);
                    break;
                case AdRewardConfListDTO::_status:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'adrc_status='. intval($val);
                    break;
            }
        }
        $isFail             = false;
        $sql                = 'SELECT SQL_CALC_FOUND_ROWS adrc_id, adrc_type, adrc_adid, adrc_key, adrc_remark, adrc_status, adrc_create_time, adrc_update_time FROM '.$this->DbAuto->getTableNameAll('ad_reward_config').$whereString.' ORDER BY adrc_id DESC '.$limitString;
        $list               = $this->DbAuto->getData($sql, $isFail);
        $totalNum           = $this->DbAuto->getDataInt('SELECT FOUND_ROWS() as num', 'num');
        if($isFail) return null;
        $AdRewardConfVOList = [];
        if(CommArray::isForeach($list))foreach($list as $item){
            $adrcIdItem             = intval($item['adrc_id']??0);
            if($adrcIdItem < 1) continue;
            $AdRewardConfVO         = $this->getAdRewardConfVO($item);
            if(!($AdRewardConfVO instanceof AdRewardConfVO)) continue;
            $AdRewardConfVOList[]   = $AdRewardConfVO;
        }
        $AdRewardConfListVO         = new AdRewardConfListVO();
        $AdRewardConfListVO->setList($AdRewardConfVOList);
        $AdRewardConfListVO->setPage($Page->getPageVO($totalNum));
        return $AdRewardConfListVO;
    }

    /**
     * @param array $adrcIdList
     * @return array
     * getAdRewardConfBatch
     */
    public function getAdRewardConfBatch(array $adrcIdList):array
    {
        $list           = $this->getAdRewardConfSrcBatch($adrcIdList);
        $listData       = [];
        if(CommArray::isForeach($list))foreach ($list as $item){
            $adrcIdItem             = intval($item['adrc_id']??0);
            if($adrcIdItem < 1) continue;
            $listData[$adrcIdItem]  = $this->getAdRewardConfVO($item);
        }
        return $listData;
    }

    /**
     * @param array $info
     * @return AdRewardConfVO|null
     * getAdRewardConfVO
     */
    public function getAdRewardConfVO(array $info):?AdRewardConfVO
    {
        $adrcId             = intval($info['adrc_id']??0);
        if($adrcId < 1) return null;
        $AdRewardConfVO     = new AdRewardConfVO();
        $AdRewardConfVO->setAdrcId($adrcId);
        $AdRewardConfVO->setType(AdRewardTypeEnum::parseValue($info['adrc_type']));
        $AdRewardConfVO->setAdId($info['adrc_adid']);
        $AdRewardConfVO->setKey($info['adrc_key']);
        $AdRewardConfVO->setRemark($info['adrc_remark']);
        $AdRewardConfVO->setStatus(YesOrNoEnum::parseValue($info['adrc_status']));
        $backUrl            = $this->backUrlList[$AdRewardConfVO->getType()]??'';
        $AdRewardConfVO->setBackUrl(str_replace('{ADID}', $AdRewardConfVO->getAdId(), $backUrl));
        $AdRewardConfVO->setCreateTime(intval($info['adrc_create_time']));
        $AdRewardConfVO->setUpdateTime(intval($info['adrc_update_time']));
        return $AdRewardConfVO;
    }


    /**
     * @param array $setData
     * @return int
     * adRewardConfAdd
     */
    public function adRewardConfAdd(array $setData):int
    {
        if(count($setData) < 1) return 0;
        $setString  = '';
        foreach ($setData as $key => $val){
            switch ($key){
                case AdRewardConfAddDTO::_type:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_type='.intval($val);
                    break;
                case AdRewardConfAddDTO::_adId:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_adid=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfAddDTO::_key:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_key=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfAddDTO::_remark:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_remark=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfAddDTO::_status:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_status='.intval($val);
                    break;
            }
        }
        if (strlen($setString) < 1) return 0;
        $currTime   = CommTime::getTimeStamp(0);
        $isFail     = false;
        $sql        = 'INSERT INTO '.$this->DbAuto->getTableNameAll('ad_reward_config').' SET '.$setString.', adrc_delete=0, adrc_create_time='.$currTime.', adrc_update_time='.$currTime;
        $adrcId     = $this->DbAuto->getDataId($sql, $isFail);
        if($isFail || $adrcId < 1) return 0;
        return $adrcId;
    }

    /**
     * @param int $adrcId
     * @param array $setData
     * @return bool
     * adRewardConfEdit
     */
    public function adRewardConfEdit(int $adrcId, array $setData):bool
    {
        if($adrcId < 1 || count($setData) < 1) return false;
        $setString  = '';
        foreach ($setData as $key => $val){
            switch ($key){
                case AdRewardConfEditDTO::_type:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_type='.intval($val);
                    break;
                case AdRewardConfEditDTO::_adId:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_adid=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfEditDTO::_key:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_key=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfEditDTO::_remark:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_remark=\''. $this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case AdRewardConfEditDTO::_status:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'adrc_status='.intval($val);
                    break;
            }
        }
        if(strlen($setString) < 1) return false;
        $isFail     = false;
        $currTime   = CommTime::getTimeStamp(0);
        $sql        = 'UPDATE '.$this->DbAuto->getTableNameAll('ad_reward_config').' SET '.$setString.', adrc_update_time='.$currTime.' WHERE adrc_id='.$adrcId.' AND adrc_delete=0';
        if($this->DbAuto->getDataNum($sql, $isFail) < 1 || $isFail) return false;
        return true;
    }
}